package com.booking.springrestful.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.booking.springrestful.domain.*;
import com.booking.springrestful.domain.dto.UserDto;
import com.booking.springrestful.exception.BusinessException;
import com.booking.springrestful.mapper.*;
import com.booking.springrestful.resp.PageResult;
import com.booking.springrestful.resp.ResultCodeEnum;
import com.booking.springrestful.service.UsersService;
import com.booking.springrestful.utills.MD5Utils;
import com.booking.springrestful.utills.StatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.OffsetDateTime;
import java.util.*;


/**
* @author 13182
* @description 针对表【users】的数据库操作Service实现
* @createDate 2024-10-28 15:42:04
*/
@Service
@Slf4j
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users>
    implements UsersService {


    @Resource
    private UsersMapper usersMapper;

    @Resource
    private AppointmentsMapper appointmentsMapper;

    @Resource
    private FeedbackMapper feedbackMapper;

    @Resource
    private UserassessmentsMapper userassessmentsMapper;

    @Resource
    private CounselorscheduleMapper counselorscheduleMapper;

    @Resource
    private CounselorsMapper counselorsMapper;

    @Resource
    private UseranalyticsMapper useranalyticsMapper;


    @Override
    public Users userLogin(String username, String password) {
        boolean exists = usersMapper.exists(new QueryWrapper<Users>().eq("username", username));
        if (!exists){
            throw new BusinessException(ResultCodeEnum.INTERNAL_SERVER_ERROR,"账号不存在");
        }else {
            Users users = usersMapper.selectOne(new QueryWrapper<Users>().eq("username", username));
            if (!Objects.equals(users.getPassword(), MD5Utils.formPassToDBPass(password))){
                throw new BusinessException(ResultCodeEnum.INTERNAL_SERVER_ERROR,"密码错误");
            }else {
                return users;
            }
        }

    }

    @Override
    public void userRegister(Users users) {
        log.info(users.getUsertype());
        boolean exists = usersMapper.exists(new QueryWrapper<Users>().eq("username", users.getUsername()));
        if (exists){
            throw new BusinessException(ResultCodeEnum.INTERNAL_SERVER_ERROR,"账号已存在");
        }else {
            Users user = new Users();
            String password = users.getPassword();
            if (password.length() <= 3 || password.length() > 8) {
                throw new BusinessException(ResultCodeEnum.INTERNAL_SERVER_ERROR,"密码长度必须在3到8位");
            }
            BeanUtils.copyProperties(users,user);
            user.setPassword(MD5Utils.formPassToDBPass(user.getPassword()));
            log.info(user.toString());
            usersMapper.insert(user);
            //如果是咨询师新增咨询师信息
            /*if (Objects.equals(user.getUsertype(), "counselor")){
                Counselors counselors = new Counselors();
                Users one = usersMapper.selectOne(new QueryWrapper<Users>().eq("username", users.getUsername()));
                counselors.setUserid(one.getUserid());
                counselorsMapper.insert(counselors);
            }*/
        }
    }

    @Override
    public Users getUser(HttpServletRequest request) {
        Object name = request.getAttribute("userName");
        if (name!=null){
            return usersMapper.selectOne(new QueryWrapper<Users>().eq("username", name.toString()));
        }else {
            return null;
        }

    }

    @Override
    public void changePass(String userName, String currentPassword, String newPassword) {
        if (newPassword.length() <= 3 || newPassword.length() > 8) {
            throw new BusinessException(ResultCodeEnum.INTERNAL_SERVER_ERROR,"密码长度必须在3到8位");
        }
        String password = usersMapper.selectOne(new QueryWrapper<Users>().eq("username", userName)).getPassword();
        if (!MD5Utils.formPassToDBPass(currentPassword).equals(password)){
            throw new BusinessException(ResultCodeEnum.INTERNAL_SERVER_ERROR,"原密码输入错误");
        }else {
            Users users = new Users();
            users.setPassword(MD5Utils.formPassToDBPass(newPassword));
            usersMapper.update(users,new QueryWrapper<Users>().eq("username", userName));
        }
    }

    @Override
    public void userUpdate(String userName, Users user) {
        if(user.getRealname().isEmpty()){
            throw new BusinessException(ResultCodeEnum.INTERNAL_SERVER_ERROR,"姓名为必填项");
        }
        if(user.getPhone().isEmpty()){
            throw new BusinessException(ResultCodeEnum.INTERNAL_SERVER_ERROR,"电话为必填项");
        }
        if(user.getGender().isEmpty()){
            throw new BusinessException(ResultCodeEnum.INTERNAL_SERVER_ERROR,"性别为必填项");
        }

        usersMapper.update(user,new QueryWrapper<Users>().eq("username", userName));
    }

    @Override
    public PageResult<Users> getUserClient(UserDto userDto, String type) {

        log.info(userDto.toString());

        //传入姓名，性别，日期
        String realname = userDto.getRealname();
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("status");
        wrapper.eq("userType",type).orderByDesc("updatedAt");
        if (StringUtils.isNotBlank(realname)){
            wrapper.like("realname",realname);
        }
        String gender = userDto.getGender();
        if (StringUtils.isNotBlank(gender)){
            wrapper.eq("gender",gender);
        }
        Date beginDate = userDto.getBeginDate();
        Date endDate = userDto.getEndDate();
        if (beginDate != null && endDate != null) {
            wrapper.between("createdAt", beginDate, endDate);
        }



        long pageSize = userDto.getPageSize();
        long current = userDto.getCurrent();

        IPage<Users> page = new Page<>(current, pageSize); // 创建分页对象

        // 进行分页查询
        IPage<Users> resultPage = usersMapper.selectPage(page, wrapper);

        // 创建包含数据和分页信息的对象
        PageResult<Users> pageResult = new PageResult<>();
        pageResult.setTotal(resultPage.getTotal());
        pageResult.setData(resultPage.getRecords());
        return pageResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class) // 当抛出Exception及其子类时回滚
    public void deleteClient(ArrayList<Users> userList, String type) {
        if (Objects.equals(type, "client")){
            //如果有预约记录未完成，禁止删除
            for (Users user : userList) {
                if (appointmentsMapper.exists(new QueryWrapper<Appointments>()
                        .eq("userId",user.getUserid())
                        .eq("status", StatusEnum.SCHEDULED))) {
                    log.info("存在来访者有预约记录未完成");
                    throw new BusinessException(ResultCodeEnum.INTERNAL_SERVER_ERROR,"来访者存在预约记录未完成");
                }

                QueryWrapper<Feedback> eqFeed = new QueryWrapper<Feedback>().eq("userId", user.getUserid());
                if (feedbackMapper.exists(eqFeed)){
                    feedbackMapper.delete(eqFeed);
                }

                QueryWrapper<Userassessments> eqAss = new QueryWrapper<Userassessments>().eq("userId", user.getUserid());
                if (userassessmentsMapper.exists(eqAss)){
                    userassessmentsMapper.delete(eqAss);
                }
                usersMapper.deleteById(user);
            }
        }else if (Objects.equals(type, "counselor")){
            for (Users user : userList) {
                log.info(user.toString());
                //先查看启用状态
                if(counselorscheduleMapper.exists(new QueryWrapper<Counselorschedule>().eq("counselorId",user.getUserid()))){
                    counselorscheduleMapper.delete(new QueryWrapper<Counselorschedule>().eq("counselorId",user.getUserid()));
                }
                QueryWrapper<Counselors> eqCou = new QueryWrapper<Counselors>().eq("userId", user.getUserid());
                if (counselorsMapper.exists(eqCou.eq("status",1))){
                    throw new BusinessException(ResultCodeEnum.INTERNAL_SERVER_ERROR,"咨询师启用状态禁止删除");
                }else {
                    counselorsMapper.delete(eqCou);
                }

                QueryWrapper<Useranalytics> eqAna = new QueryWrapper<Useranalytics>().eq("userId", user.getUserid());
                if (useranalyticsMapper.exists(eqAna)){
                    useranalyticsMapper.delete(eqAna);
                }
                usersMapper.deleteById(user);

            }
        }else {
            for (Users user : userList) {
                usersMapper.deleteById(user);
            }
        }


    }

    @Override
    public void updateClient(Users users) {
        Users one = usersMapper.selectOne(new QueryWrapper<Users>().eq("userId", users.getUserid()));
        if (!(Objects.equals(one.getPassword(), users.getPassword()))){
            users.setPassword(MD5Utils.formPassToDBPass(users.getPassword()));
        }
        usersMapper.updateById(users);
    }

    @Override
    public Boolean checkCon() {
        return usersMapper.exists(new QueryWrapper<Users>().eq("status", "2"));
    }

    @Override
    public Boolean conSuccess(String userName) {
        Users one = usersMapper.selectOne(new QueryWrapper<Users>().eq("username", userName));
        if (Objects.equals(one.getStatus(), "1") && (Objects.equals(one.getIspop(), "0")||one.getIspop()==null)){
            //弹出 然后插入
            Users users = new Users();
            users.setIspop("1");
            usersMapper.update(users,new QueryWrapper<Users>().eq("username", userName));
            return true;
        }else {
            return false;
        }
    }

    @Override
    public List<Counselorschedule> getWorkTime(Integer userid) {
        Integer counselorid = counselorsMapper.selectOne(new QueryWrapper<Counselors>().eq("userId", userid)).getCounselorid();
        List<Counselorschedule> list = counselorscheduleMapper.selectList(new QueryWrapper<Counselorschedule>().eq("counselorId", counselorid));
        return list;
    }

    @Override
    public Integer getCouId(Integer userid) {
        Counselors counselors = counselorsMapper.selectOne(new QueryWrapper<Counselors>().eq("userId", userid));
        return counselors.getCounselorid();
    }


}




